import Node from './Node';

export default class Layer extends Node {
  addChild() {
    for (const i in arguments) {
      if (arguments[i] instanceof Node) {
        if (this.childs.indexOf(arguments[i]) === -1) {
          arguments[i].canvas = this.canvas;
          arguments[i].parent = this;
          this.childs.push(arguments[i]);
          // if (arguments[i] instanceof Layer) {
          //   arguments[i].build()
          // }
        }
      }
    }
    this.childs.sort((a, b) => (a.zIndex - b.zIndex));
  }

  removeChild(child) {
    if (this.childs.indexOf(child) !== -1) {
      this.childs.splice(this.childs.indexOf(child), 1);
    }
  }

  clearEventListener() {
    for (let i = 0; i < this.childs.length; i++) {
      this.childs[i].clearEventListener();
    }
    super.clearEventListener();
  }

  get borderTopWidth() {
    if (this.borderTop && this.borderTop !== '') {
      let borderTopDesc = this.borderTop.split(' ');
      if (borderTopDesc.length >= 2) {
        return Number(borderTopDesc[1].replace('px', ''));
      }
    }
    return 0;
  }

  get borderBottomWidth() {
    if (this.borderBottom && this.borderBottom !== '') {
      let borderBottomDesc = this.borderBottom.split(' ');
      if (borderBottomDesc.length >= 2) {
        return Number(borderBottomDesc[1].replace('px', ''));
      }
    }
    return 0;
  }

  build() {
    return false;
  }

  draw (painter) {

  }

  paint(config) {
    if (this.visible) {
      config.before && config.before(this);
      const { painter } = this.canvas;
      painter.save();
      painter.beginPath();
      painter.rect(
        this.left,
        this.canvas.height - this.height - this.bottom + this.borderBottomWidth,
        this.width,
        this.height + this.borderBottomWidth + this.borderTopWidth
      );
      painter.clip();
      this.build(painter);
      super.paint(config);
      for (const child of this.childs) {
        child.paint(config);
      }
      config.after && config.after(this);
      painter.restore();
    }
  }

  containsPoint (point) {
    return (
      point.x <= this.left + this.width
      && point.x >= this.left
      && point.y <= this.bottom + this.height
      && point.y >= this.bottom
    );
  }
}
